/**
 * Copyright(c) kyle.
 */
package org.example.JUC;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁测试
 * <p>
 * 对比ReentrantLock
 *
 * @author kyle
 * @version 1.00.00
 * @updateUser [Kyle]
 * @updateRemark [说明本次修改内容]
 * @date [2020-06-21 16:23]
 * @since [2020-06-21 16:23]
 */
public class ReadWriteLockDemo {
    private static final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(false);
    public static final Lock readLock = readWriteLock.readLock();
    public static final Lock writeLock = readWriteLock.writeLock();
    private static final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        final ReadWriteLockDemo demo = new ReadWriteLockDemo();
        Runnable readRunnable = () -> {
            try {
                demo.handleRead(readLock);
                //                demo.handleRead(lock);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Runnable writeRunnable = new Runnable() {
            public final Random r = new Random();

            @Override
            public void run() {
                try {
                    demo.handleWrite(writeLock, r.nextInt());
                    //                demo.handleWrite(lock, r.nextInt());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        for (int i = 0; i < 18; i++) {
            new Thread(readRunnable).start();
        }
        for (int i = 0; i < 18; i++) {
            new Thread(writeRunnable).start();
        }
    }

    public void handleRead(Lock lock) throws InterruptedException {
        try {
            lock.lock();
            System.out.println("操作读取");
            Thread.sleep(1000);
        } finally {
            System.out.println(Thread.currentThread().getName() + "完成读取");
            lock.unlock();
        }
    }

    public void handleWrite(Lock lock, int index) throws InterruptedException {
        try {
            lock.lock();
            System.out.println("操作写入");
            Thread.sleep(1000);
            Thread.yield();
        } finally {
            System.out.println("完成写入");
            lock.unlock();
        }
    }
}
